package me.helllp.book.concurrent.ch05;

import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class Consumer implements Runnable{
	private BlockingQueue<PCData> queue;
	private static final int SLEEPTIME = 1000;
	
	public Consumer(BlockingQueue<PCData> queue) {
		this.queue = queue;
	}
	
	@Override
	public void run() {
		System.out.println("开始消费 id = " + Thread.currentThread().getId());
		Random r = new Random();
		
		try {
			while(true){
				//	获取任务
				PCData data = queue.poll(1000, TimeUnit.MILLISECONDS);
				
				if(null != data){
					//	计算平方
					int re = data.getData() * data.getData();
					System.out.println(MessageFormat.format("{0} * {1} = {2}", data.getData(), data.getData(), re));
					Thread.sleep(r.nextInt(SLEEPTIME));
				}else{
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
		}
	}
}
